package com.platform.utils;

import com.platform.comm.constants.GlobalConstant;
import com.platform.comm.enums.YnEnum;
import com.platform.enums.CommFlagType;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.converter.BidirectionalConverter;
import ma.glasnost.orika.metadata.Type;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * description: 映射
 *
 * @author lx
 */
@Component
public class ObjectConverter {


    public static class  YenumConverter extends BidirectionalConverter<Object, YnEnum> {

        @Override
        public YnEnum convertTo(Object source, Type<YnEnum> destinationType, MappingContext mappingContext) {
            return YnEnum.valueOf(source.toString());
        }

        @Override
        public Object convertFrom(YnEnum source, Type<Object> destinationType, MappingContext mappingContext) {
            return source.name();
        }
    }



    public static class  CommFlagConverter extends BidirectionalConverter<Object, CommFlagType> {

        @Override
        public CommFlagType convertTo(Object source, Type<CommFlagType> destinationType, MappingContext mappingContext) {
            return CommFlagType.getFlagByValue(source.toString());
        }

        @Override
        public Object convertFrom(CommFlagType source, Type<Object> destinationType, MappingContext mappingContext) {
            return source.getFvalue();
        }
    }


    public static class  LocalDateTimeConverter extends BidirectionalConverter<Object, LocalDateTime> {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(GlobalConstant.DATE_TIME_PATTERN);

        @Override
        public LocalDateTime convertTo(Object source, Type<LocalDateTime> destinationType, MappingContext mappingContext) {

            return source==null?null:LocalDateTime.parse(source.toString(),df);
        }

        @Override
        public Object convertFrom(LocalDateTime source, Type<Object> destinationType, MappingContext mappingContext) {

            return source==null?null:df.format(source);
        }
    }

}
